from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.contrib.auth.hashers import make_password, check_password
from .models import Video, DubanUser, UserLikeVideo, Comment, VideoComment, Article, Picture, ArticlePicture, ArticleComment
from django.utils import timezone
from django.core.exceptions import ObjectDoesNotExist
from django.core import serializers
import os


# Create your views here.


def videolist(request):
    try:
        page_index = int(request.GET['pageIndex'])
        limit = int(request.GET['limit'])
    except UnicodeDecodeError:
        return JsonResponse({"code": "0", "msg": "参数不正确"})
    else:
        video_list = Video.objects.get_queryset().order_by('create_date')
        paginator = Paginator(video_list, limit)
        user = None
        if 'HTTP_SESSIONTOKEN' in request.META:
            try:
                user = DubanUser.objects.get(session_token=request.META['HTTP_SESSIONTOKEN'])
            except Exception as e:
                return JsonResponse({"code": "-1", "msg": "您已被登出，请重新登录"})
        try:
            datas = paginator.page(page_index).object_list
        except PageNotAnInteger:
            return JsonResponse({"code": "0", "msg": "参数不正确"})
        except EmptyPage:
            return JsonResponse({"code": "1", "msg": "请求成功", "data": []})
        else:
            result_list = []
            for index in range(0, len(datas)):
                video_object = datas[index]
                like_count = UserLikeVideo.objects.filter(video=video_object).count()
                comment_count = video_object.video_comments.count()
                isCollected = "0"
                if user is not None:
                    try:
                        UserLikeVideo.objects.get(user=user, video=video_object)
                    except:
                        isCollected = "0"
                    else:
                        isCollected = "1"

                video = {'videoId': video_object.id,
                         'videoCover': video_object.video_cover,
                         'videoName': video_object.video_name,
                         'videoContentType': video_object.video_type_des,
                         'videoRank': str(video_object.video_rank),
                         'collectCount': like_count,
                         'commentCount': comment_count,
                         'isCollected': isCollected}
                result_list.append(video)

            return JsonResponse({"code": "1", "msg": "请求成功", "data": result_list})


def myVideolist(request):
    if 'HTTP_SESSIONTOKEN' in request.META:
        try:
            user = DubanUser.objects.get(session_token=request.META['HTTP_SESSIONTOKEN'])
        except Exception as e:
            return JsonResponse({"code": "-1", "msg": "您已被登出，请重新登录"})
        else:
            try:
                page_index = int(request.GET['pageIndex'])
                limit = int(request.GET['limit'])
            except UnicodeDecodeError:
                return JsonResponse({"code": "0", "msg": "参数不正确"})
            else:
                video_list = user.like_videos.all()
                paginator = Paginator(video_list, limit)
                try:
                    datas = paginator.page(page_index).object_list
                except PageNotAnInteger:
                    return JsonResponse({"code": "0", "msg": "参数不正确"})
                except EmptyPage:
                    return JsonResponse({"code": "1", "msg": "请求成功", "data": []})
                else:
                    result_list = []
                    for index in range(0, len(datas)):
                        video_object = datas[index]
                        like_count = UserLikeVideo.objects.filter(video=video_object).count()
                        isCollected = "1"
                        video = {'videoId': video_object.id,
                                 'videoCover': video_object.video_cover,
                                 'videoName': video_object.video_name,
                                 'videoContentType': video_object.video_type_des,
                                 'videoRank': str(video_object.video_rank),
                                 'collectCount': like_count,
                                 'isCollected': isCollected}
                        result_list.append(video)

                    return JsonResponse({"code": "1", "msg": "请求成功", "data": result_list})
    else:
        return JsonResponse({"code": "0", "msg": "参数不正确"})


def singUp(request):
    try:
        mobile = request.POST['mobile']
        password = request.POST['password']
        code = request.POST['code']
    except UnicodeDecodeError:
        return JsonResponse({"code": "0", "msg": "参数不正确"})
    else:
        user = DubanUser()
        user.user_name = '用户' + mobile[7:]
        user.mobile_phone = mobile
        user.password = make_password(password)
        user.session_token = make_password(str(timezone.now()) + code)
        # 获取设备的公共参数生成sessionToken
        try:
            user.save()
        except Exception as e:
            return JsonResponse({"code": "0", "msg": "注册失败"})
        else:
            return JsonResponse({"code": "1", "msg": "注册", "data": {'userName': user.user_name,
                                                                    'userId': user.id,
                                                                    'mobile': user.mobile_phone,
                                                                    'sessionToken': user.session_token}})


def singIn(request):
    try:
        mobile = request.GET['mobile']
        password = request.GET['password']
    except UnicodeDecodeError:
        return JsonResponse({"code": "0", "msg": "参数不正确"})
    else:
        try:
            user = DubanUser.objects.get(mobile_phone=mobile)
        except:
            return JsonResponse({"code": "0", "msg": "当前用户不存在"})
        else:
            if not check_password(password, user.password):
                return JsonResponse({"code": "0", "msg": "密码错误"})
            else:
                user.session_token = make_password(str(timezone.now()))
                try:
                    user.save()
                except:
                    return JsonResponse({"code": "0", "msg": "登录失败"})
                else:
                    responseData = {'userName': user.user_name,
                                    'userId': user.id,
                                    'mobile': user.mobile_phone,
                                    'like_video_count': user.like_videos.all().count(),
                                    'like_article_count': user.like_article.all().count(),
                                    'sessionToken': user.session_token}

                    return JsonResponse({"code": "1", "msg": "登录成功", "data": responseData})


def likeVideo(request):
    try:
        sessionToken = request.META['HTTP_SESSIONTOKEN']
        videoId = request.POST['videoId']
    except:
        return JsonResponse({"code": "0", "msg": "参数不正确"})
    else:
        if DubanUser.objects.get(session_token=sessionToken) is not None:
            user = DubanUser.objects.get(session_token=sessionToken)
            if Video.objects.get(pk=videoId) is not None:
                video = Video.objects.get(pk=videoId)
                try:
                    UserLikeVideo.objects.get(user=user, video=video)
                except ObjectDoesNotExist:
                    userLikeVideo = UserLikeVideo(user=user, video=video)
                    try:
                        userLikeVideo.save()
                    except:
                        return JsonResponse({"code": "0", "msg": "收藏失败"})
                    else:
                        return JsonResponse({"code": "1", "msg": "收藏成功"})
                else:
                    return JsonResponse({"code": "0", "msg": "您已收藏该视频"})
            else:
                return JsonResponse({"code": "0", "msg": "该视频不存在"})
        else:
            return JsonResponse({"code": "-1", "msg": "您已被登出，请重新登录"})


def unlikeVideo(request):
    try:
        sessionToken = request.META['HTTP_SESSIONTOKEN']
        videoId = request.POST['videoId']
    except:
        return JsonResponse({"code": "0", "msg": "参数不正确"})
    else:
        if DubanUser.objects.get(session_token=sessionToken) is not None:
            user = DubanUser.objects.get(session_token=sessionToken)
            if Video.objects.get(pk=videoId) is not None:
                video = Video.objects.get(pk=videoId)
                try:
                    UserLikeVideo.objects.get(user=user, video=video)
                except ObjectDoesNotExist:
                    return JsonResponse({"code": "0", "msg": "您未收藏该视频"})
                else:
                    userLikeVideo = UserLikeVideo.objects.get(user=user, video=video)
                    try:
                        userLikeVideo.delete()
                    except:
                        return JsonResponse({"code": "0", "msg": "操作失败"})
                    else:
                        return JsonResponse({"code": "1", "msg": "操作成功"})
            else:
                return JsonResponse({"code": "0", "msg": "该视频不存在"})
        else:
            return JsonResponse({"code": "-1", "msg": "您已被登出，请重新登录"})


def commentList(request):
    try:
        videoId = request.GET['videoId']
        page_index = int(request.GET['pageIndex'])
        limit = int(request.GET['limit'])
    except:
        return JsonResponse({"code": "0", "msg": "参数不正确"})
    else:
        try:
            video = Video.objects.get(pk=videoId)
        except ObjectDoesNotExist:
            return JsonResponse({"code": "0", "msg": "该视频不存在"})
        else:
            comment_list = video.video_comments.all().order_by('create_date')
            paginator = Paginator(comment_list, limit)
            try:
                datas = paginator.page(page_index).object_list
            except PageNotAnInteger:
                return JsonResponse({"code": "0", "msg": "参数不正确"})
            except EmptyPage:
                return JsonResponse({"code": "1", "msg": "请求成功", "data": []})
            else:
                result_list = []
                for index in range(0, len(datas)):
                    comment_object = datas[index]
                    user = DubanUser.objects.get(id=comment_object.user_id)
                    toUser = None
                    if comment_object.to_user_id is not None:
                        toUser = DubanUser.objects.get(id=comment_object.to_user_id)
                    comment = {'comment_id': comment_object.id,
                               'content': comment_object.content,
                               'user_id': user.id,
                               'user_name': user.user_name,
                               'to_user_id': toUser.id if toUser is not None else '',
                               'to_user_name': toUser.user_name if toUser is not None else '',
                               'create_time': comment_object.create_date,
                               }
                    result_list.append(comment)
                return JsonResponse({"code": "1", "msg": "请求成功", "data": result_list})

def articleCommentList(request):
    try:
        articleId = request.GET['articleId']
        page_index = int(request.GET['pageIndex'])
        limit = int(request.GET['limit'])
    except:
        return JsonResponse({"code": "0", "msg": "参数不正确"})
    else:
        try:
            article = Article.objects.get(pk=articleId)
        except ObjectDoesNotExist:
            return JsonResponse({"code": "0", "msg": "该文章不存在"})
        else:
            comment_list = article.article_comments.all().order_by('create_date')
            paginator = Paginator(comment_list, limit)
            try:
                datas = paginator.page(page_index).object_list
            except PageNotAnInteger:
                return JsonResponse({"code": "0", "msg": "参数不正确"})
            except EmptyPage:
                return JsonResponse({"code": "1", "msg": "请求成功", "data": []})
            else:
                result_list = []
                for index in range(0, len(datas)):
                    comment_object = datas[index]
                    user = DubanUser.objects.get(id=comment_object.user_id)
                    toUser = None
                    if comment_object.to_user_id is not None:
                        toUser = DubanUser.objects.get(id=comment_object.to_user_id)
                    comment = {'comment_id': comment_object.id,
                               'content': comment_object.content,
                               'user_id': user.id,
                               'user_name': user.user_name,
                               'to_user_id': toUser.id if toUser is not None else '',
                               'to_user_name': toUser.user_name if toUser is not None else '',
                               'create_time': comment_object.create_date,
                               }
                    result_list.append(comment)
                return JsonResponse({"code": "1", "msg": "请求成功", "data": result_list})


def addComment(request):
    if 'type' in request.POST and request.POST['type'] == 'video':
        try:
            videoId = request.POST['videoId']
            content = request.POST['content']
        except:
            return JsonResponse({"code": "0", "msg": "参数不正确"})
        else:
            if Video.objects.get(pk=videoId) is not None:
                video = Video.objects.get(pk=videoId)
                if 'HTTP_SESSIONTOKEN' in request.META:
                    sessionToken = request.META['HTTP_SESSIONTOKEN']
                    if DubanUser.objects.get(session_token=sessionToken) is not None:
                        user = DubanUser.objects.get(session_token=sessionToken)
                        comment = Comment()
                        comment.user_id = user.id
                        comment.content = content
                        if 'to_user_id' in request.POST:
                            comment.to_user_id = request.POST['to_user_id']
                        try:
                            comment.save()
                        except Exception as e:
                            print(e)
                            return JsonResponse({"code": "0", "msg": "评论失败"})
                        else:
                            video_comment = VideoComment(video=video, comment=comment)
                            try:
                                video_comment.save()
                            except:
                                return JsonResponse({"code": "0", "msg": "评论失败"})
                            else:
                                return JsonResponse({"code": "1", "msg": "评论成功"})
                    else:
                        return JsonResponse({"code": "-1", "msg": "您已被登出，请重新登录"})
                else:
                    return JsonResponse({"code": "0", "msg": "您还未登录，请登录后再执行操作"})
            else:
                return JsonResponse({"code": "0", "msg": "该视频不存在"})
    elif 'type' in request.POST and request.POST['type'] == 'article':
        try:
            articleId = request.POST['articleId']
            content = request.POST['content']
        except:
            return JsonResponse({"code": "0", "msg": "参数不正确"})
        else:
            if Article.objects.get(pk=articleId) is not None:
                article = Article.objects.get(pk=articleId)
                if 'HTTP_SESSIONTOKEN' in request.META:
                    sessionToken = request.META['HTTP_SESSIONTOKEN']
                    if DubanUser.objects.get(session_token=sessionToken) is not None:
                        user = DubanUser.objects.get(session_token=sessionToken)
                        comment = Comment()
                        comment.user_id = user.id
                        comment.content = content
                        if 'to_user_id' in request.POST:
                            comment.to_user_id = request.POST['to_user_id']
                        try:
                            comment.save()
                        except Exception as e:
                            print(e)
                            return JsonResponse({"code": "0", "msg": "评论失败"})
                        else:
                            article_comment = ArticleComment(article=article, comment=comment)
                            try:
                                article_comment.save()
                            except:
                                return JsonResponse({"code": "0", "msg": "评论失败"})
                            else:
                                return JsonResponse({"code": "1", "msg": "评论成功"})
                    else:
                        return JsonResponse({"code": "-1", "msg": "您已被登出，请重新登录"})
                else:
                    return JsonResponse({"code": "0", "msg": "您还未登录，请登录后再执行操作"})
            else:
                return JsonResponse({"code": "0", "msg": "该视频不存在"})
    else:
        return JsonResponse({"code": "0", "msg": "参数不正确"})

def deleteComment(request):
    try:
        comment_id = request.POST['comment_id']
    except:
        return JsonResponse({"code": "0", "msg": "参数不正确"})
    else:
        if 'HTTP_SESSIONTOKEN' in request.META:
            sessionToken = request.META['HTTP_SESSIONTOKEN']
            if DubanUser.objects.get(session_token=sessionToken) is not None:
                user = DubanUser.objects.get(session_token=sessionToken)
                if Comment.objects.get(pk=comment_id) is not None:
                    comment = Comment.objects.get(pk=comment_id)
                    if comment.user_id != user.id:
                        return JsonResponse({"code": "0", "msg": "不能删除不是自己的评论"})
                    else:
                        video_comment = VideoComment.objects.get(comment=comment)
                        try:
                            video_comment.delete()
                        except:
                            return JsonResponse({"code": "0", "msg": "操作失败"})
                        else:
                            return JsonResponse({"code": "1", "msg": "操作成功"})
                else:
                    return JsonResponse({"code": "0", "msg": "找不到评论"})
            else:
                return JsonResponse({"code": "-1", "msg": "您已被登出，请重新登录"})
        else:
            return JsonResponse({"code": "0", "msg": "您还未登录，请登录后再执行操作"})


def createArticle(request):
        if 'HTTP_SESSIONTOKEN' in request.META:
            sessionToken = request.META['HTTP_SESSIONTOKEN']
            if DubanUser.objects.get(session_token=sessionToken) is not None:
                user = DubanUser.objects.get(session_token=sessionToken)
                try:
                    title = request.POST['title']
                    content = request.POST['content']
                except Exception as e:
                    return JsonResponse({"code": "0", "msg": "参数不正确"})
                else:
                    # 先生成文章
                    article = Article(auther=user, title=title, content=content)
                    # 保存图片
                    try:
                        article.save()
                    except:
                        return JsonResponse({"code": "0", "msg": "创建失败"})
                    else:
                        img_files = request.FILES.getlist('image')
                        successCount = 0
                        for img in img_files:
                            picture = Picture()
                            picture.image = img
                            try:
                                picture.save()
                            except:
                                break
                            else:
                                articlePicture = ArticlePicture(article=article, image=picture)
                                articlePicture.save()
                                successCount += 1
                        if successCount == len(img_files):
                            return JsonResponse({"code": "1", "msg": "创建成功，图片均已保存"})
                        else:
                            return JsonResponse({"code": "1", "msg": "创建成功，图片未完全保存"})
            else:
                return JsonResponse({"code": "-1", "msg": "您已被登出，请重新登录"})
        else:
            return JsonResponse({"code": "0", "msg": "您还未登录，请先登录"})


def articleList(request):
    try:
        page_index = int(request.GET['pageIndex'])
        limit = int(request.GET['limit'])
    except UnicodeDecodeError:
        return JsonResponse({"code": "0", "msg": "参数不正确"})
    else:
        article_list = Article.objects.get_queryset().order_by('create_date')
        paginator = Paginator(article_list, limit)
        user = None
        if 'HTTP_SESSIONTOKEN' in request.META:
            try:
                user = DubanUser.objects.get(session_token=request.META['HTTP_SESSIONTOKEN'])
            except ObjectDoesNotExist:
                return JsonResponse({"code": "-1", "msg": "您已被登出，请重新登录"})
        try:
            datas = paginator.page(page_index).object_list
        except PageNotAnInteger:
            return JsonResponse({"code": "0", "msg": "参数不正确"})
        except EmptyPage:
            return JsonResponse({"code": "1", "msg": "请求成功", "data": []})
        else:
            result_list = []
            for index in range(0, len(datas)):
                article_object = datas[index]
                image_list = []
                if article_object.images.count() > 0:
                    images = article_object.images.all()
                    for x in range(0, images.count()):
                        picture = images[x]
                        image_list.append('http://192.168.3.53:8000/'+picture.image.url)
                comment_count = article_object.article_comments.count()
                autherUser = DubanUser.objects.get(pk=article_object.auther.id)
                article = {'article_id': article_object.id,
                           'article_title': article_object.title,
                           'content': article_object.content,
                           'type': 'image' if len(image_list) > 0 else 'text',
                           'images': image_list,
                           'username': autherUser.user_name,
                           'user_id': autherUser.id,
                           'commentCount': comment_count,
                           'avatar': ('http://192.168.3.53:8000/' + autherUser.avatar.url) if  autherUser.avatar and hasattr(autherUser.avatar, 'url') is not None else None}
                result_list.append(article)
            return JsonResponse({"code": "1", "msg": "请求成功", "data": result_list})


def userArticleList(request):
            try:
                page_index = int(request.GET['pageIndex'])
                limit = int(request.GET['limit'])
            except UnicodeDecodeError:
                return JsonResponse({"code": "0", "msg": "参数不正确"})
            else:
                user = None
                if 'user_id' in request.GET:
                    try:
                        user = DubanUser.objects.get(pk=request.GET('user_id'))
                    except:
                        return JsonResponse({"code": "0", "msg": "参数不正确"})
                else:
                    try:
                        user = DubanUser.objects.get(session_token=request.META['HTTP_SESSIONTOKEN'])
                    except Exception as e:
                        return JsonResponse({"code": "-1", "msg": "您已被登出，请重新登录"})
                try:
                    article_list = Article.objects.filter(auther=user).order_by('create_date')
                    paginator = Paginator(article_list, limit)
                    datas = paginator.page(page_index).object_list
                except PageNotAnInteger:
                    return JsonResponse({"code": "0", "msg": "参数不正确"})
                except EmptyPage:
                    return JsonResponse({"code": "1", "msg": "请求成功", "data": []})
                else:
                    result_list = []
                    for index in range(0, len(datas)):
                        article_object = datas[index]
                        image_list = []
                        if article_object.images.count() > 0:
                            images = article_object.images.all()
                            for x in range(0, images.count()):
                                picture = images[x]
                                image_list.append('http://192.168.3.53:8000/' + picture.image.url)
                        comment_count = article_object.article_comments.count()
                        autherUser = DubanUser.objects.get(pk=article_object.auther.id)
                        article = {'article_id': article_object.id,
                                   'article_title': article_object.title,
                                   'content': article_object.content,
                                   'type': 'image' if len(image_list) > 0 else 'text',
                                   'images': image_list,
                                   'username': autherUser.user_name,
                                   'user_id': autherUser.id,
                                   'commentCount': comment_count,
                                   'avatar': ('http://192.168.3.53:8000/' + autherUser.avatar.url) if autherUser.avatar and hasattr(
                                       autherUser.avatar, 'url') is not None else None}
                        result_list.append(article)
                    return JsonResponse({"code": "1", "msg": "请求成功", "data": result_list})